<?php
class ModelSaleOrder extends Model {
	public function deleteOrder($order_id) {
		
		$order_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "order` WHERE order_status_id > '0' AND order_id = '" . (int)$order_id . "'");

		if ($order_query->num_rows) {
			$product_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_product WHERE order_id = '" . (int)$order_id . "'");

			foreach($product_query->rows as $product) {
			
				if (isset($product['subtract'])) {
					$this->db->query("UPDATE `" . DB_PREFIX . "product` SET quantity = (quantity + " . (int)$product['quantity'] . ") WHERE product_id = '" . (int)$product['product_id'] . "'");

					$option_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_option WHERE order_id = '" . (int)$order_id . "' AND order_product_id = '" . (int)$product['order_product_id'] . "'");

					foreach ($option_query->rows as $option) {
						$this->db->query("UPDATE " . DB_PREFIX . "product_option_value SET quantity = (quantity + " . (int)$product['quantity'] . ") WHERE product_option_value_id = '" . (int)$option['product_option_value_id'] . "' AND subtract = '1'");
					}
				}
			}
		}     		

		$this->db->query("DELETE FROM `" . DB_PREFIX . "order` WHERE order_id = '" . (int)$order_id . "'");
      	$this->db->query("DELETE FROM " . DB_PREFIX . "order_history WHERE order_id = '" . (int)$order_id . "'");
      	$this->db->query("DELETE FROM " . DB_PREFIX . "order_product WHERE order_id = '" . (int)$order_id . "'");
      	$this->db->query("DELETE FROM " . DB_PREFIX . "order_option WHERE order_id = '" . (int)$order_id . "'");
	  	$this->db->query("DELETE FROM " . DB_PREFIX . "order_download WHERE order_id = '" . (int)$order_id . "'");
      	$this->db->query("DELETE FROM " . DB_PREFIX . "order_total WHERE order_id = '" . (int)$order_id . "'");
	}

	public function addProduct($order_id, $data) {
   		$this->db->query("INSERT INTO " . DB_PREFIX . "order_product SET order_id = '" . (int)$order_id . "', product_id = '" . (int)$data['product_id'] . "', name = '" . $this->db->escape($data['name']) . "', model = '" . $this->db->escape($data['model']) . "', price = '" . (float)$data['price'] . "', total = '" . (float)$data['total'] . "', tax = '" . (float)$data['tax'] . "', quantity = '" . (int)$data['quantity'] . "'");

		$order_product_id = $this->db->getLastId();

		foreach ($data['options'] as $option) {
   			$this->db->query("INSERT INTO " . DB_PREFIX . "order_option SET order_id = '" . (int)$order_id . "', order_product_id = '" . (int)$order_product_id . "', product_option_value_id = '" . (int)$option['product_option_value_id'] . "', name = '" . $this->db->escape($option['name']) . "', value = '" . $this->db->escape($option['value']) . "', price = '" . (float)$option['price'] . "', prefix = '" . $this->db->escape($option['prefix']) . "'");
		}

		$this->db->query("UPDATE `" . DB_PREFIX . "order` SET total = '" . (float)$data['new_grand_total'] . "' WHERE order_id = '" . (int)$order_id . "'");

		$totals = $this->getOrderTotals($order_id);

		$subtotal = reset($totals); //Assume first total is subtotal

		$this->db->query("UPDATE " . DB_PREFIX . "order_total SET text = '" . $this->db->escape($data['formatted_order_total']) . "', value = '" . (float)$data['order_total'] . "' WHERE order_id = '" . (int)$order_id . "' AND order_total_id = '" . $subtotal['order_total_id'] . "'");

		$total = end($totals); //Assume last total is grand total

		$this->db->query("UPDATE " . DB_PREFIX . "order_total SET text = '" . $this->db->escape($data['formatted_grand_total']) . "', value = '" . (float)$data['new_grand_total'] . "' WHERE order_id = '" . (int)$order_id . "' AND order_total_id = '" . $total['order_total_id'] . "'");

		return $order_product_id;
	}

	public function removeProduct($order_id, $data) {
		$this->db->query("UPDATE `" . DB_PREFIX . "order` SET total = '" . (float)$data['total'] . "' WHERE order_id = '" . (int)$order_id . "'");		
		
		foreach($data['total_data'] as $total_item){
			$sql = "UPDATE " . DB_PREFIX . "order_total SET text = '" . $this->db->escape($total_item['text']) . "', value = '" . (float)$total_item['value'] . "' WHERE order_id = '" . (int)$order_id . "' AND order_total_id = '" . (int)$total_item['total_id'] . "'";
			$this->db->query($sql);
		}
		
   		$this->db->query("DELETE FROM " . DB_PREFIX . "order_product WHERE order_id = '" . (int)$order_id . "' AND  order_product_id = '" . (int)$data['order_product_id'] . "'");
		$this->db->query("DELETE FROM " . DB_PREFIX . "order_option WHERE order_id = '" . (int)$order_id . "' AND  order_product_id = '" . (int)$data['order_product_id'] . "'");
	}
	
	public function editProduct($order_id, $data) {
		$this->db->query("UPDATE `" . DB_PREFIX . "order` SET total = '" . (float)$data['total'] . "' WHERE order_id = '" . (int)$order_id . "'");		
		
		foreach($data['total_data'] as $total_item){
			$sql = "UPDATE " . DB_PREFIX . "order_total SET text = '" . $this->db->escape($total_item['text']) . "', value = '" . (float)$total_item['value'] . "' WHERE order_id = '" . (int)$order_id . "' AND order_total_id = '" . (int)$total_item['total_id'] . "'";
			$this->db->query($sql);
		}
		
   		$this->db->query("UPDATE " . DB_PREFIX . "order_product SET total = '" . (float)$data['update_quantity']['total'] . "', quantity = '" . (int)$data['update_quantity']['quantity'] . "' WHERE order_id = '" . (int)$order_id . "' AND  order_product_id = '" . (int)$data['order_product_id'] . "'");		
	}
	
	public function editShipping($order_id, $data) {
		$this->db->query("UPDATE `" . DB_PREFIX . "order` SET total = '" . (float)$data['total'] . "' WHERE order_id = '" . (int)$order_id . "'");		
		
		foreach($data['total_data'] as $total_item){
			$sql = "UPDATE " . DB_PREFIX . "order_total SET text = '" . $this->db->escape($total_item['text']) . "', value = '" . (float)$total_item['value'] . "' WHERE order_id = '" . (int)$order_id . "' AND order_total_id = '" . (int)$total_item['total_id'] . "'";
			$this->db->query($sql);
		}		
	}
	
	public function removeProductOld($order_id, $data) {
		$this->db->query("UPDATE `" . DB_PREFIX . "order` SET total = '" . (float)$data['new_grand_total'] . "' WHERE order_id = '" . (int)$order_id . "'");		

		$totals = $this->getOrderTotals($order_id);

		$subtotal = reset($totals); //Assume first total is subtotal

		$this->db->query("UPDATE " . DB_PREFIX . "order_total SET text = '" . $this->db->escape($data['formatted_order_total']) . "', value = '" . (float)$data['order_total'] . "' WHERE order_id = '" . (int)$order_id . "' AND order_total_id = '" . $subtotal['order_total_id'] . "'");

		$total = end($totals);

		$this->db->query("UPDATE " . DB_PREFIX . "order_total SET text = '" . $this->db->escape($data['formatted_grand_total']) . "', value = '" . (float)$data['new_grand_total'] . "' WHERE order_id = '" . (int)$order_id . "' AND order_total_id = '" . $total['order_total_id'] . "'");
   		$this->db->query("DELETE FROM " . DB_PREFIX . "order_product WHERE order_id = '" . (int)$order_id . "' AND  order_product_id = '" . (int)$data['order_product_id'] . "'");
   		$this->db->query("DELETE FROM " . DB_PREFIX . "order_option WHERE order_id = '" . (int)$order_id . "' AND  order_product_id = '" . (int)$data['order_product_id'] . "'");
	}
	
	public function updateShippingAddress($order_id, $data) {
        echo "UPDATE `" . DB_PREFIX . "order` SET shipping_firstname = '" . $this->db->escape($data['shipping_firstname']) . "', shipping_lastname = '" . $this->db->escape($data['shipping_lastname']) . "', shipping_company = '" . $this->db->escape($data['shipping_company']) . "', shipping_address_1 = '" . $this->db->escape($data['shipping_address_1']) . "', shipping_address_2 = '" . $this->db->escape($data['shipping_address_2']) . "', shipping_city = '" . $this->db->escape($data['shipping_city']) . "', shipping_postcode = '" . $this->db->escape($data['shipping_postcode']) . "', shipping_zone = '" . $this->db->escape($data['shipping_zone']) . "', shipping_zone_id = '" . (int)$data['shipping_zone_id'] . "', shipping_country = '" . $this->db->escape($data['shipping_country']) . "', shipping_country_id = '" . (int)$data['shipping_country_id'] . "', shipping_street_no = '" . $this->db->escape($data['shipping_street_no']) . "', date_modified = NOW() WHERE order_id = '" . (int)$order_id . "'";
		$this->db->query("UPDATE `" . DB_PREFIX . "order` SET shipping_firstname = '" . $this->db->escape($data['shipping_firstname']) . "', shipping_lastname = '" . $this->db->escape($data['shipping_lastname']) . "', shipping_company = '" . $this->db->escape($data['shipping_company']) . "', shipping_address_1 = '" . $this->db->escape($data['shipping_address_1']) . "', shipping_address_2 = '" . $this->db->escape($data['shipping_address_2']) . "', shipping_city = '" . $this->db->escape($data['shipping_city']) . "', shipping_postcode = '" . $this->db->escape($data['shipping_postcode']) . "', shipping_zone = '" . $this->db->escape($data['shipping_zone']) . "', shipping_zone_id = '" . (int)$data['shipping_zone_id'] . "', shipping_country = '" . $this->db->escape($data['shipping_country']) . "', shipping_country_id = '" . (int)$data['shipping_country_id'] . "', shipping_street_no = '" . $this->db->escape($data['shipping_street_no']) . "', date_modified = NOW() WHERE order_id = '" . (int)$order_id . "'");
	}

	public function updatePaymentAddress($order_id, $data) {
		$this->db->query("UPDATE `" . DB_PREFIX . "order` SET payment_firstname = '" . $this->db->escape($data['payment_firstname']) . "', payment_lastname = '" . $this->db->escape($data['payment_lastname']) . "', payment_company = '" . $this->db->escape($data['payment_company']) . "', payment_address_1 = '" . $this->db->escape($data['payment_address_1']) . "', payment_address_2 = '" . $this->db->escape($data['payment_address_2']) . "', payment_city = '" . $this->db->escape($data['payment_city']) . "', payment_postcode = '" . $this->db->escape($data['payment_postcode']) . "', payment_zone = '" . $this->db->escape($data['payment_zone']) . "', payment_zone_id = '" . (int)$data['payment_zone_id'] . "', payment_country = '" . $this->db->escape($data['payment_country']) . "', payment_country_id = '" . (int)$data['payment_country_id'] . "', street_no = '" . $this->db->escape($data['street_no']) . "', date_modified = NOW() WHERE order_id = '" . (int)$order_id . "'");
	}

	public function addOrderHistory($order_id, $data) {
		$this->db->query("UPDATE `" . DB_PREFIX . "order` SET order_status_id = '" . (int)$data['order_status_id'] . "', date_modified = NOW() WHERE order_id = '" . (int)$order_id . "'");

		if ($data['append']) {
			$this->db->query("INSERT INTO " . DB_PREFIX . "order_history SET order_id = '" . (int)$order_id . "', order_status_id = '" . (int)$data['order_status_id'] . "', notify = '" . (isset($data['notify']) ? (int)$data['notify'] : 0) . "', comment = '" . $this->db->escape(strip_tags($data['comment'])) . "', date_added = NOW()");
		}

      	if ($data['notify']) {
            $this->sendMail($order_id, $data);
            return;
            
        	$order_query = $this->db->query("SELECT *, os.name AS status FROM `" . DB_PREFIX . "order` o LEFT JOIN " . DB_PREFIX . "order_status os ON (o.order_status_id = os.order_status_id AND os.language_id = o.language_id) LEFT JOIN " . DB_PREFIX . "language l ON (o.language_id = l.language_id) WHERE o.order_id = '" . (int)$order_id . "'");

			if ($order_query->num_rows) {
				$language = new Language($order_query->row['directory']);
				$language->load($order_query->row['filename']);
				$language->load('mail/order');

				$this->load->model('setting/store');

				$subject = sprintf($language->get('text_subject'), $order_query->row['store_name'], $order_id);

				$message  = $language->get('text_order') . ' ' . $order_id . "\n";
				$message .= $language->get('text_date_added') . ' ' . date($language->get('date_format_short'), strtotime($order_query->row['date_added'])) . "\n\n";
				$message .= $language->get('text_order_status') . "\n\n";
				$message .= $order_query->row['status'] . "\n\n";
				$message .= $language->get('text_invoice') . "\n";
				$message .= html_entity_decode($order_query->row['store_url'] . 'index.php?route=account/invoice&order_id=' . $order_id, ENT_QUOTES, 'UTF-8') . "\n\n";

				if ($data['comment']) {
					$message .= $language->get('text_comment') . "\n\n";
					$message .= strip_tags(html_entity_decode($data['comment'], ENT_QUOTES, 'UTF-8')) . "\n\n";
				}

				$message .= $language->get('text_footer');

				$mail = new Mail();
				$mail->protocol = $this->config->get('config_mail_protocol');
				$mail->hostname = $this->config->get('config_smtp_host');
				$mail->username = $this->config->get('config_smtp_username');
				$mail->password = $this->config->get('config_smtp_password');
				$mail->port = $this->config->get('config_smtp_port');
				$mail->timeout = $this->config->get('config_smtp_timeout');
				$mail->setTo($order_query->row['email']);
				$mail->setFrom($this->config->get('config_email'));
	    		$mail->setSender($order_query->row['store_name']);
	    		$mail->setSubject($subject);
	    		$mail->setText(html_entity_decode($message, ENT_QUOTES, 'UTF-8'));
	    		$mail->send();
			}
		}
	}

    private function sendMail($order_id, $data){
        $order_query = $this->db->query("SELECT *, l.filename AS filename, l.directory AS directory FROM `" . DB_PREFIX . "order` o LEFT JOIN " . DB_PREFIX . "language l ON (o.language_id = l.language_id) WHERE o.order_id = '" . (int)$order_id . "'");
         
        if ($order_query->num_rows) {
            $language = new Language($order_query->row['directory']);
            $language->load($order_query->row['filename']);
            $language->load('mail/order_confirm');
            $order_status_id = $data['order_status_id'];
            $this->load->model('localisation/currency');
            
            $order_status_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_status WHERE order_status_id = '" . (int)$order_status_id . "' AND language_id = '" . (int)$order_query->row['language_id'] . "'");
            $order_product_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_product WHERE order_id = '" . (int)$order_id . "'");
            $order_total_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_total WHERE order_id = '" . (int)$order_id . "' ORDER BY sort_order ASC");
            $order_download_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_download WHERE order_id = '" . (int)$order_id . "'");
            
            $subject = sprintf($language->get('text_subject'), $order_query->row['store_name'], $order_id);
                
            // HTML Mail
            $template = new Template();
            
            $template->data['title'] = sprintf($language->get('text_subject'), html_entity_decode($order_query->row['store_name'], ENT_QUOTES, 'UTF-8'), $order_id);
                
            $template->data['text_greeting'] = sprintf($language->get('text_greeting'), html_entity_decode($order_query->row['store_name'], ENT_QUOTES, 'UTF-8'));
            $template->data['text_order_detail'] = $language->get('text_order_detail');
            $template->data['text_order_id'] = $language->get('text_order_id');
            $template->data['text_invoice'] = $language->get('text_invoice');
            $template->data['text_date_added'] = $language->get('text_date_added');
            $template->data['text_telephone'] = $language->get('text_telephone');
            $template->data['text_email'] = $language->get('text_email');
            $template->data['text_ip'] = $language->get('text_ip');
            $template->data['text_fax'] = $language->get('text_fax');        
            $template->data['text_shipping_address'] = $language->get('text_shipping_address');
            $template->data['text_payment_address'] = $language->get('text_payment_address');
            $template->data['text_shipping_method'] = $language->get('text_shipping_method');
            $template->data['text_payment_method'] = $language->get('text_payment_method');
            $template->data['text_comment'] = $language->get('text_comment');
            $template->data['text_powered_by'] = $language->get('text_powered_by');
            $template->data['text_order_status'] = $language->get('text_order_status');
            
            $template->data['column_product'] = $language->get('column_product');
            $template->data['column_model'] = $language->get('column_model');
            $template->data['column_quantity'] = $language->get('column_quantity');
            $template->data['column_price'] = $language->get('column_price');
            $template->data['column_total'] = $language->get('column_total');
                    
            $template->data['order_id'] = $order_id;
            $template->data['customer_id'] = $order_query->row['customer_id'];    
            $template->data['date_added'] = date($language->get('date_format_short'), strtotime($order_query->row['date_added']));        
            $template->data['logo'] = 'cid:' . basename($this->config->get('config_logo'));
            $template->data['store_name'] = $order_query->row['store_name'];
            $template->data['address'] = nl2br($this->config->get('config_address'));
            $template->data['telephone'] = $this->config->get('config_telephone');
            $template->data['fax'] = $this->config->get('config_fax');
            $template->data['email'] = $this->config->get('config_email');
            $template->data['store_url'] = $order_query->row['store_url'];
            $template->data['invoice'] = $order_query->row['store_url'] . 'index.php?route=account/invoice&order_id=' . $order_id;
            $template->data['firstname'] = $order_query->row['firstname'];
            $template->data['lastname'] = $order_query->row['lastname'];
            $template->data['shipping_method'] = $order_query->row['shipping_method'];
            $template->data['payment_method'] = $order_query->row['payment_method'];
            $template->data['customer_email'] = $order_query->row['email'];
            $template->data['customer_telephone'] = $order_query->row['telephone'];                
            $template->data['customer_ip'] = $order_query->row['ip'];
            $template->data['order_status'] = $order_status_query->row['name'];             
            $template->data['comment'] = nl2br($order_query->row['comment']);
			//$template->data['history_comment'] = (isset($data['comment']) ? nl2br($data['comment']) : '');
			$template->data['history_comment'] = (isset($data['comment']) ? html_entity_decode($data['comment'], ENT_QUOTES, 'UTF-8') : '');			
            //$template->data['comment'] .= ($template->data['comment'] ? '<br />' : '') . (isset($data['comment']) ? nl2br($data['comment']) : ''); 
            //$template->data['comment'] = nl2br($data['comment']) . '<br />'; 
            //$template->data['comment'] .= $language->get('text_order_status') . ' ' . $order_status_query->row['name'] . "\n\n";
            if($order_query->row['payment_method_id'] == 'bank_transfer'){
                $template->data['payment_comment'] = $comment = $this->config->get('bank_transfer_bank_1');
            }
            else{
                $template->data['payment_comment'] = $this->config->get('quickpay_description');   
            }
            $template->data['shipping_method_note'] = $order_query->row['shipping_method_id'] != 'free.free' ? '' : $language->get('text_free_shipping'); //$this->language->get('text_free_shipping');            
            $template->data['payment_method_note'] = $order_query->row['payment_method_id'] != 'bank_transfer' ? '' : $language->get('text_payment_note');
            
            $zone_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE zone_id = '" . (int)$order_query->row['shipping_zone_id'] . "'");
            
            if ($zone_query->num_rows) {
                $zone_code = $zone_query->row['code'];
            } else {
                $zone_code = '';
            }
            
            if ($order_query->row['shipping_address_format']) {
                $format = $order_query->row['shipping_address_format'];
            } else {
                $format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
            }
                
            $find = array(
                '{firstname}',
                '{lastname}',
                '{company}',
                '{address_1}',
                '{address_2}',
                '{city}',
                '{postcode}',
                '{zone}',
                '{zone_code}',
                '{country}'
            );
        
            $replace = array(
                'firstname' => $order_query->row['shipping_firstname'],
                'lastname'  => $order_query->row['shipping_lastname'],
                'company'   => $order_query->row['shipping_company'],
                'address_1' => $order_query->row['shipping_address_1'],
                'address_2' => $order_query->row['shipping_address_2'],
                'city'      => $order_query->row['shipping_city'],
                'postcode'  => $order_query->row['shipping_postcode'],
                'zone'      => $order_query->row['shipping_zone'],
                'zone_code' => $zone_code,
                'country'   => $order_query->row['shipping_country']  
            );
            
            $template->data['shipping_address'] = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));

            $zone_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE zone_id = '" . (int)$order_query->row['payment_zone_id'] . "'");
            
            if ($zone_query->num_rows) {
                $zone_code = $zone_query->row['code'];
            } else {
                $zone_code = '';
            }
            
            if ($order_query->row['payment_address_format']) {
                $format = $order_query->row['payment_address_format'];
            } else {
                $format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
            }
                
            $find = array(
                '{firstname}',
                '{lastname}',
                '{company}',
                '{address_1}',
                '{address_2}',
                '{city}',
                '{postcode}',
                '{zone}',
                '{zone_code}',
                '{country}'
            );
            
            $replace = array(
                'firstname' => $order_query->row['payment_firstname'],
                'lastname'  => $order_query->row['payment_lastname'],
                'company'   => $order_query->row['payment_company'],
                'address_1' => $order_query->row['payment_address_1'],
                'address_2' => $order_query->row['payment_address_2'],
                'city'      => $order_query->row['payment_city'],
                'postcode'  => $order_query->row['payment_postcode'],
                'zone'      => $order_query->row['payment_zone'],
                'zone_code' => $zone_code,
                'country'   => $order_query->row['payment_country']  
            );
            
            $template->data['payment_address'] = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));
            
            if($order_query->row['extra_name'] && $order_query->row['extra_company'] && $order_query->row['extra_address'] && $order_query->row['extra_postcode']){
                $template->data['extra_address'] = array(
                    'name'      => $order_query->row['extra_name'], 
                    'company'   => $order_query->row['extra_company'], 
                    'address'   => $order_query->row['extra_address'], 
                    'postcode'  => $order_query->row['extra_postcode'], 
                );
            }
            else{
                $template->data['extra_address'] = null;
            }
            
            $template->data['products'] = array();                  
            foreach ($order_product_query->rows as $product) {
                $option_data = array();
                
                $order_option_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_option WHERE order_id = '" . (int)$order_id . "' AND order_product_id = '" . (int)$product['order_product_id'] . "'");
                
                foreach ($order_option_query->rows as $option) {
                    $option_data[] = array(
                        'name'  => $option['name'],
                        'value' => $option['value'],
                        'product_number'    => $option['product_number'],
                    );
                }
              
                $template->data['products'][] = array(
                    'name'     => $product['name'],
                    'model'    => $product['model'],
                    'option'   => $option_data,
                    'quantity' => $product['quantity'],
                    'price'    => $this->currency->formatPrice($product['price'], $order_query->row['currency'], $order_query->row['value']),
                    'total'    => $this->currency->formatPrice($product['total'], $order_query->row['currency'], $order_query->row['value']),
                    'product_number'      => $product['sku'],
                );
            }

            $template->data['totals'] = $order_total_query->rows;          
            $html = $template->fetch('mail/order_confirm.tpl'); 

            // Text Mail
            $text  = sprintf($language->get('text_greeting'), html_entity_decode($order_query->row['store_name'], ENT_QUOTES, 'UTF-8')) . "\n\n";
            $text .= $language->get('text_order_id') . ' ' . $order_id . "\n";
            $text .= $language->get('text_date_added') . ' ' . date($language->get('date_format_short'), strtotime($order_query->row['date_added'])) . "\n";
            $text .= $language->get('text_order_status') . ' ' . $order_status_query->row['name'] . "\n\n";
            $text .= $language->get('text_product') . "\n";
            
            foreach ($order_product_query->rows as $result) {
                $text .= $result['quantity'] . 'x ' . $result['name'] . ' (' . $result['model'] . ') ' . html_entity_decode($this->currency->format($result['total'], $order_query->row['currency'], $order_query->row['value']), ENT_NOQUOTES, 'UTF-8') . "\n";
                $order_option_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_option WHERE order_id = '" . (int)$order_id . "' AND order_product_id = '" . $result['order_product_id'] . "'");
                foreach ($order_option_query->rows as $option) {
                    $text .= chr(9) . '-' . $option['name'] . ' ' . $option['value'] . "\n";
                }
            }
            
            $text .= "\n";
            
            $text .= $language->get('text_total') . "\n";
            
            foreach ($order_total_query->rows as $result) {
                $text .= $result['title'] . ' ' . html_entity_decode($result['text'], ENT_NOQUOTES, 'UTF-8') . "\n";
            }            
            
            $order_total = $result['text'];
            
            $text .= "\n";
            
            if ($order_query->row['customer_id']) {
                $text .= $language->get('text_invoice') . "\n";
                $text .= $order_query->row['store_url'] . 'index.php?route=account/invoice&order_id=' . $order_id . "\n\n";
            }
        
            if ($order_download_query->num_rows) {
                $text .= $language->get('text_download') . "\n";
                $text .= $order_query->row['store_url'] . 'index.php?route=account/download' . "\n\n";
            }
            
            $comment = ($data['comment'] != '') ? ($data['comment'] .  "\n\n") : '';                
            if ($comment) {
                $text .= $language->get('text_comment') . "\n\n";
                $text .= $comment . "\n\n";
            }
            
            $text .= $language->get('text_footer');
                        
            $mail = new Mail(); 
            $mail->protocol = $this->config->get('config_mail_protocol');
            $mail->parameter = $this->config->get('config_mail_parameter');
            $mail->hostname = $this->config->get('config_smtp_host');
            $mail->username = $this->config->get('config_smtp_username');
            $mail->password = $this->config->get('config_smtp_password');
            $mail->port = $this->config->get('config_smtp_port');
            $mail->timeout = $this->config->get('config_smtp_timeout');            
            $mail->setTo($order_query->row['email']);
            $mail->setFrom($this->config->get('config_email'));
            //$mail->setSender($order_query->row['store_name']);
            $mail->setSender(html_entity_decode($this->config->get('config_name'), ENT_QUOTES, 'UTF-8'));
            $mail->setSubject($subject);
            $mail->setHtml($html);
            $mail->setText(html_entity_decode($text, ENT_QUOTES, 'UTF-8'));
            $mail->addAttachment(DIR_IMAGE . $this->config->get('config_logo'));
            $mail->send();
			
			/*
			require_once(DIR_MAILER . 'mwc_mailer.php');        
			$mail = new MwcMailer(); 
			if($this->config->get('config_mail_protocol') == 'smtp'){           
				$mail->Host = $this->config->get('config_smtp_host');
				$mail->Username = $this->config->get('config_smtp_username');
				$mail->Password = $this->config->get('config_smtp_password');
				$mail->Port = $this->config->get('config_smtp_port');            
			
				$mail->IsSMTP();
			}
                
			$mail->setFrom($this->config->get('config_email'), $this->config->get('config_email'));                     
			$mail->Subject = $subject;
			$mail->MsgHTML($html);
			$mail->addAttachment(DIR_IMAGE . $this->config->get('config_logo'), DIR_IMAGE . $this->config->get('config_logo'));
			$mail->AddAddress($order_query->row['email']);
            $mail->send();
			*/
        }
    }
    
	public function getOrder($order_id) {
		$order_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "order` WHERE order_id = '" . (int)$order_id . "'");

		if ($order_query->num_rows) {
			$country_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "country` WHERE country_id = '" . (int)$order_query->row['shipping_country_id'] . "'");

			if ($country_query->num_rows) {
				$shipping_iso_code_2 = $country_query->row['iso_code_2'];
				$shipping_iso_code_3 = $country_query->row['iso_code_3'];
			} else {
				$shipping_iso_code_2 = '';
				$shipping_iso_code_3 = '';
			}

			$zone_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE zone_id = '" . (int)$order_query->row['shipping_zone_id'] . "'");

			if ($zone_query->num_rows) {
				$shipping_zone_code = $zone_query->row['code'];
			} else {
				$shipping_zone_code = '';
			}

			$country_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "country` WHERE country_id = '" . (int)$order_query->row['payment_country_id'] . "'");

			if ($country_query->num_rows) {
				$payment_iso_code_2 = $country_query->row['iso_code_2'];
				$payment_iso_code_3 = $country_query->row['iso_code_3'];
			} else {
				$payment_iso_code_2 = '';
				$payment_iso_code_3 = '';
			}

			$zone_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE zone_id = '" . (int)$order_query->row['payment_zone_id'] . "'");

			if ($zone_query->num_rows) {
				$payment_zone_code = $zone_query->row['code'];
			} else {
				$payment_zone_code = '';
			}

			$order_data = array(
				'order_id'                => $order_query->row['order_id'],
				'invoice_id'              => $order_query->row['invoice_id'],
				'invoice_prefix'          => $order_query->row['invoice_prefix'],
				'store_id'                => $order_query->row['store_id'],
				'store_name'              => $order_query->row['store_name'],
				'store_url'               => $order_query->row['store_url'],
				'customer_id'             => $order_query->row['customer_id'],
				'customer_group_id'       => $order_query->row['customer_group_id'],
				'firstname'               => $order_query->row['firstname'],
				'lastname'                => $order_query->row['lastname'],
				'telephone'               => $order_query->row['telephone'],
				'fax'                     => $order_query->row['fax'],
				'email'                   => $order_query->row['email'],
				'shipping_firstname'      => $order_query->row['shipping_firstname'],
				'shipping_lastname'       => $order_query->row['shipping_lastname'],
				'shipping_company'        => $order_query->row['shipping_company'],
				'shipping_address_1'      => $order_query->row['shipping_address_1'],
				'shipping_address_2'      => $order_query->row['shipping_address_2'],
				'shipping_postcode'       => $order_query->row['shipping_postcode'],
				'shipping_city'           => $order_query->row['shipping_city'],
				'shipping_zone_id'        => $order_query->row['shipping_zone_id'],
				'shipping_zone'           => $order_query->row['shipping_zone'],
				'shipping_zone_code'      => $shipping_zone_code,
				'shipping_country_id'     => $order_query->row['shipping_country_id'],
				'shipping_country'        => $order_query->row['shipping_country'],
				'shipping_iso_code_2'     => $shipping_iso_code_2,
				'shipping_iso_code_3'     => $shipping_iso_code_3,
				'shipping_address_format' => $order_query->row['shipping_address_format'],
				'shipping_method'         => $order_query->row['shipping_method'],
				'payment_firstname'       => $order_query->row['payment_firstname'],
				'payment_lastname'        => $order_query->row['payment_lastname'],
				'payment_company'         => $order_query->row['payment_company'],
				'payment_address_1'       => $order_query->row['payment_address_1'],
				'payment_address_2'       => $order_query->row['payment_address_2'],
				'payment_postcode'        => $order_query->row['payment_postcode'],
				'payment_city'            => $order_query->row['payment_city'],
				'payment_zone_id'         => $order_query->row['payment_zone_id'],
				'payment_zone'            => $order_query->row['payment_zone'],
				'payment_zone_code'       => $payment_zone_code,
				'payment_country_id'      => $order_query->row['payment_country_id'],
				'payment_country'         => $order_query->row['payment_country'],
				'payment_iso_code_2'      => $payment_iso_code_2,
				'payment_iso_code_3'      => $payment_iso_code_3,
				'payment_address_format'  => $order_query->row['payment_address_format'],
				'payment_method'          => $order_query->row['payment_method'],
				'comment'                 => $order_query->row['comment'],
				'total'                   => $order_query->row['total'],
				'order_status_id'         => $order_query->row['order_status_id'],
				'language_id'             => $order_query->row['language_id'],
				'currency_id'             => $order_query->row['currency_id'],
				'currency'                => $order_query->row['currency'],
				'value'                   => $order_query->row['value'],
				'coupon_id'               => $order_query->row['coupon_id'],
				'date_modified'           => $order_query->row['date_modified'],
				'date_added'              => $order_query->row['date_added'],
				'ip'                      => $order_query->row['ip'],
                'shipping_method_id'      => $order_query->row['shipping_method_id'],
                'payment_method_id'       => $order_query->row['payment_method_id'],
				'street_no'       		  => $order_query->row['street_no'],
                'shipping_street_no'	  => $order_query->row['shipping_street_no'],
			);

			return $order_data;
		} else {
			return FALSE;
		}
	}

	public function getOrders($data = array()) {
		$sql = "SELECT o.order_id, CONCAT(o.firstname, ' ', o.lastname) AS name, (SELECT os.name FROM " . DB_PREFIX . "order_status os WHERE os.order_status_id = o.order_status_id AND os.language_id = '" . (int)$this->config->get('config_language_id') . "') AS status, o.date_added, o.total, o.currency, o.value FROM `" . DB_PREFIX . "order` o";

		if (isset($data['filter_order_status_id']) && !is_null($data['filter_order_status_id'])) {
			$sql .= " WHERE o.order_status_id = '" . (int)$data['filter_order_status_id'] . "'";
		} else {
			$sql .= " WHERE o.order_status_id > '0'";
		}

		if (isset($data['filter_order_id']) && !is_null($data['filter_order_id'])) {
			$sql .= " AND o.order_id = '" . (int)$data['filter_order_id'] . "'";
		}

		if (isset($data['filter_name']) && !is_null($data['filter_name'])) {
			$sql .= " AND LCASE(CONCAT(o.firstname, ' ', o.lastname)) LIKE '%" . $this->db->escape(strtolower($data['filter_name'])) . "%'";
		}

		if (isset($data['filter_date_added']) && !is_null($data['filter_date_added'])) {
			$sql .= " AND DATE(o.date_added) = DATE('" . $this->db->escape($data['filter_date_added']) . "')";
		}

		if (isset($data['filter_total']) && !is_null($data['filter_total'])) {
			$sql .= " AND o.total = '" . (float)$data['filter_total'] . "'";
		}

		$sort_data = array(
			'o.order_id',
			'name',
			'status',
			'o.date_added',
			'o.total',
		);

		if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
			$sql .= " ORDER BY " . $data['sort'];
		} else {
			$sql .= " ORDER BY o.order_id";
		}

		if (isset($data['order']) && ($data['order'] == 'DESC')) {
			$sql .= " DESC";
		} else {
			$sql .= " ASC";
		}

		if (isset($data['start']) || isset($data['limit'])) {
			if ($data['start'] < 0) {
				$data['start'] = 0;
			}

			if ($data['limit'] < 1) {
				$data['limit'] = 20;
			}

			$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
		}

		$query = $this->db->query($sql);

		return $query->rows;
	}

	public function generateInvoiceId($order_id) {
		$query = $this->db->query("SELECT MAX(invoice_id) AS invoice_id FROM `" . DB_PREFIX . "order`");

		if ($query->row['invoice_id']) {
			$invoice_id = (int)$query->row['invoice_id'] + 1;
		} elseif ($this->config->get('config_invoice_id')) {
			$invoice_id = $this->config->get('config_invoice_id');
		} else {
			$invoice_id = 1;
		}

		$this->db->query("UPDATE `" . DB_PREFIX . "order` SET invoice_id = '" . (int)$invoice_id . "', invoice_prefix = '" . $this->db->escape($this->config->get('config_invoice_prefix')) . "', date_modified = NOW() WHERE order_id = '" . (int)$order_id . "'");

		return $this->config->get('config_invoice_prefix') . $invoice_id;
	}

	public function getOrderProducts($order_id) {
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_product WHERE order_id = '" . (int)$order_id . "'");

		return $query->rows;
	}

	public function getOrderOptions($order_id, $order_product_id) {
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_option WHERE order_id = '" . (int)$order_id . "' AND order_product_id = '" . (int)$order_product_id . "'");

		return $query->rows;
	}

	public function getOrderTotals($order_id) {
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_total WHERE order_id = '" . (int)$order_id . "' ORDER BY sort_order");

		return $query->rows;
	}

	public function getOrderHistory($order_id) {
		$query = $this->db->query("SELECT oh.date_added, os.name AS status, oh.comment, oh.notify FROM " . DB_PREFIX . "order_history oh LEFT JOIN " . DB_PREFIX . "order_status os ON oh.order_status_id = os.order_status_id WHERE oh.order_id = '" . (int)$order_id . "' AND os.language_id = '" . (int)$this->config->get('config_language_id') . "' ORDER BY oh.date_added");

		return $query->rows;
	}

	public function getOrderDownloads($order_id) {
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_download WHERE order_id = '" . (int)$order_id . "' ORDER BY name");

		return $query->rows;
	}

	public function getTotalOrders($data = array()) {
      	$sql = "SELECT COUNT(*) AS total FROM `" . DB_PREFIX . "order`";

		if (isset($data['filter_order_status_id']) && !is_null($data['filter_order_status_id'])) {
			$sql .= " WHERE order_status_id = '" . (int)$data['filter_order_status_id'] . "'";
		} else {
			$sql .= " WHERE order_status_id > '0'";
		}

		if (isset($data['filter_order_id']) && !is_null($data['filter_order_id'])) {
			$sql .= " AND order_id = '" . (int)$data['filter_order_id'] . "'";
		}

		if (isset($data['filter_name']) && !is_null($data['filter_name'])) {
			$sql .= " AND CONCAT(firstname, ' ', lastname) LIKE '%" . $this->db->escape($data['filter_name']) . "%'";
		}

		if (isset($data['filter_date_added']) && !is_null($data['filter_date_added'])) {
			$sql .= " AND DATE(date_added) = DATE('" . $this->db->escape($data['filter_date_added']) . "')";
		}

		if (isset($data['filter_total']) && !is_null($data['filter_total'])) {
			$sql .= " AND total = '" . (float)$data['filter_total'] . "'";
		}

		$query = $this->db->query($sql);

		return $query->row['total'];
	}

	public function getTotalOrdersByStoreId($store_id) {
      	$query = $this->db->query("SELECT COUNT(*) AS total FROM `" . DB_PREFIX . "order` WHERE store_id = '" . (int)$store_id . "'");

		return $query->row['total'];
	}

	public function getOrderHistoryTotalByOrderStatusId($order_status_id) {
	  	$query = $this->db->query("SELECT oh.order_id FROM " . DB_PREFIX . "order_history oh LEFT JOIN `" . DB_PREFIX . "order` o ON (oh.order_id = o.order_id) WHERE oh.order_status_id = '" . (int)$order_status_id . "' AND o.order_status_id > '0' GROUP BY order_id");

		return $query->num_rows;
	}

	public function getTotalOrdersByOrderStatusId($order_status_id) {
      	$query = $this->db->query("SELECT COUNT(*) AS total FROM `" . DB_PREFIX . "order` WHERE order_status_id = '" . (int)$order_status_id . "' AND order_status_id > '0'");

		return $query->row['total'];
	}

	public function getTotalOrdersByLanguageId($language_id) {
      	$query = $this->db->query("SELECT COUNT(*) AS total FROM `" . DB_PREFIX . "order` WHERE language_id = '" . (int)$language_id . "' AND order_status_id > '0'");

		return $query->row['total'];
	}

	public function getTotalOrdersByCurrencyId($currency_id) {
      	$query = $this->db->query("SELECT COUNT(*) AS total FROM `" . DB_PREFIX . "order` WHERE currency_id = '" . (int)$currency_id . "' AND order_status_id > '0'");

		return $query->row['total'];
	}

	public function getTotalSales() {
      	$query = $this->db->query("SELECT SUM(total) AS total FROM `" . DB_PREFIX . "order` WHERE order_status_id > '0'");

		return $query->row['total'];
	}

	public function getTotalSalesByYear($year) {
      	$query = $this->db->query("SELECT SUM(total) AS total FROM `" . DB_PREFIX . "order` WHERE order_status_id > '0' AND YEAR(date_added) = '" . (int)$year . "'");

		return $query->row['total'];
	}
}
?>
